<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="供应商">
          <el-select
            v-model="searchParam.partnerId"
            clearable
            placeholder="请选择供应商"
          >
            <el-option
              v-for="item in partners"
              :key="item.id"
              :label="item.partnerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            clearable
            placeholder="请选择工厂"
          >
            <el-option
              v-for="item in plants"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="物料号">
          <el-input
            v-model="searchParam.materialNumber"
            placeholder="请输入物料号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="采购协议号">
          <el-input
            v-model="searchParam.purchasePlanNumber"
            placeholder="请输入采购协议号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
          <el-button
            class="ml-3"
            @click="
              useDownload(
                '/srm/core/srmpurchaseplan/export',
                '采购协议',
                searchParam
              )
            "
          >
            <template #icon><i-ep-download /></template>导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />批量删除</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableBatchDisabled()"
          ><i-ep-delete />批量停用</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="供应商编号"
          prop="partnerCode"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="供应商名称"
          prop="partnerName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="工厂编号"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="工厂名称"
          prop="plantName"
          min-width="200"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="物料编号"
          prop="materialNumber"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="160"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="采购协议号"
          prop="purchasePlanNumber"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="生效日期"
          prop="beginDate"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
          :formatter="formatDate"
        />
        <el-table-column
          label="截止日期"
          prop="endDate"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
          :formatter="formatDate"
        />
        <el-table-column
          label="最大采购量"
          prop="maxPlanQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="最小采购批量"
          prop="minBatchQuantity"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <el-tag>
              <span v-show="scope.row.enabled == '0'">停用</span>
              <span v-show="scope.row.enabled == '1'">启用</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="240"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="toggleEnabled(scope.row)"
            >
              <span v-show="scope.row.enabled == '1'">停用</span>
              <span v-show="scope.row.enabled == '0'">启用</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <srmpurchaseplan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMPURCHASEPLAN",
  inheritAttrs: false,
});

let plants = ref([]);
let partners = ref([]);
let materials = ref([]);
// 请求参数
const requestApi = "/srm/core/srmpurchaseplan/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  partnerCode: "",
  plantCode: "",
  materialNumber: "",
  beginDateSearch: [],
  beginDateStart: "",
  beginDateEnd: "",
  endDateSearch: [],
  endDateStart: "",
  endDateEnd: "",
};

const deleteParam = {
  api: "/srm/core/srmpurchaseplan/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
  getPartners();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
async function getPartners() {
  const data = await request({
    url: "/srm/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}

async function getPlants() {
  const data = await request({
    url: "/srm/core/common/getPlantList",
    method: "get",
  });
  plants.value = data.data;
}

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/srm/core/srmpurchaseplan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开采购协议表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "采购协议编辑";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增采购协议";
  }
  addDialog.readvisible = false;
  addDialog.visible = true;
}

/** 打开采购协议表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "采购协议详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function handleTableBatchDisabled() {
  // 弹出确认提示框
  ElMessageBox.confirm("确定停用所选项吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(ids.value);
      try {
        loading.value = true; // 显示加载状态
        await request({
          url: "/srm/core/srmpurchaseplan/batchDisabled",
          method: "post",
          data: { ids: ids.value },
        });
        reset();
      } catch (error) {
        console.error("请求发生错误:", error);
      } finally {
        loading.value = false; // 隐藏加载状态
      }
    })
    .catch(() => {
      // 用户取消操作
      console.log("用户取消操作");
    });
}
async function toggleEnabled(row: any) {
  const text = row.enabled === 0 ? "启用" : "停用";
  // 弹出确认提示框
  ElMessageBox.confirm(`确定要${text}此记录吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true; // 显示加载状态
      request({
        url: `/srm/core/srmpurchaseplan/enabled`,
        method: "post",
        data: row,
      })
        .then((res) => {
          ElMessage.success(`${text}成功`);
          getTableList();
        })
        .catch((res) => {
          return;
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 用户取消操作
      console.log("用户取消操作");
    });
}
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
</script>
